<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends MY_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
	}

	public function index() {
        if(!$this->is_login()) {
            redirect();
        }
        $username = $this->session->userdata('username');
        $this->load->helper('bookaccess');

        // Profile Content
        $this->load->model('model_user');
        $data['user'] = $this->model_user->get_user($username);

        // Uploaded Content
        $this->load->model('model_books');
        $list = $this->model_books->getBookbyUser($username);
        $listbook = [];
        foreach($list as $book) 
        {
            $linkcover = getCover($book['id_document']);
            $book['cover'] = $linkcover;
            if($book['author'] == '') $book['author'] = "Chưa rõ";
            array_push($listbook, $book);
        }
        $data['uploaded'] = $listbook;


        // Reading Content
        $this->load->model('model_user');
        $list = $this->model_user->reading($username);
        $listbook = [];
        foreach($list as $book) 
        {

            $linkcover = getCover($book['id_document']);
            $book['cover'] = $linkcover;
            if($book['author'] == '') $book['author'] = "Chưa rõ";

            $contentTable = getTableContent($book['id_document']);
            foreach($contentTable as $node) {
                if((string)$node['id'] == $book['id_chap']) {
                    $book['name_chap'] = $node['text'];
                    break;
                }
            }
            array_push($listbook, $book);
        }
        $data['reading'] = $listbook;

        // Tags and Location
        $this->load->model('model_tags');
        $list = $this->model_tags->get_user_tag($username);
        $listbook = [];
        foreach($list as $book) 
        {
            $linkcover = getCover($book['id_document']);
            $book['cover'] = $linkcover;

            if($book['author'] == '') $book['author'] = "Chưa rõ";

            $contentTable = getTableContent($book['id_document']);
            foreach($contentTable as $node) {
                if((string)$node['id'] == $book['id_chap']) {
                    $book['name_chap'] = $node['text'];
                    break;
                }
                $book['name_chap'] = 'Gợi ý chung';
            }
            array_push($listbook, $book);
        }
        $data['tags'] = $listbook;

        //Get menu
        $data['template']['menu'] = createMenu();
        if($this->is_login())
            $data['template']['user'] = $this->session->userdata('username');

        $this->load->view('view_user', $data);
	}

	public function upload() {
        if(!$this->is_login()) redirect();

        $this->load->model('model_categories');
        $data['cat'] = $this->model_categories->getMenu();

        $this->load->model('model_user');
        $data['loca'] = $this->model_user->get_loca();

        $data['error'] = ' ';

        //Get menu
        $data['template']['menu'] = createMenu();
        if($this->is_login())
            $data['template']['user'] = $this->session->userdata('username');

		$this->load->view('view_user_upload', $data);
	}

    public function login() {

        //Get menu
        $data['template']['menu'] = createMenu();
        $data['error'] = ' ';

        //Get menu
        $data['template']['menu'] = createMenu();
        if($this->is_login())
            $data['template']['user'] = $this->session->userdata('username');
        
        $this->load->view('view_user_login', $data);
    }


	/**
	* Form functions, ajax, ...
	* 
	*/
	

//====================================================================================   
//==============================UPLOAD FUNCTION========================================
//====================================================================================

    public function get_upload(){

        if($this->is_login())
        {
            $config['upload_path'] = './assets/resource/';
            $config['allowed_types'] = 'zip|epub';
            $config['file_name'] ='';
            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            if ( ! $this->upload->do_upload())
            {
                $error = array('error' => $this->upload->display_errors());
                $this->load->view('view_user_upload', $error);
            }
            else
            {
                $title = $this->input->post('title');
                $author = $this->input->post('author');
                $descript = $this->input->post('description');
                $cate = $this->input->post('category');
                $tags = $this->input->post('tags');
                //
                $location = $this->input->post('location');
                echo $location;

                $data = array('upload_data' => $this->upload->data());
                $zip = new ZipArchive;
                $myFile = $data['upload_data']['full_path'];
                chmod($myFile,0777);

                //$myDir = $data['upload_data']['raw_name'];
                // $target = './assets/resource/'.$myDir;  
            $id = 'book01a'.rand();            
            if(! is_dir('./assets/resource/book01a'.rand()))
            { 
                
                //mkdir($id, 0777);
                $user = $this->session->userdata('username');
                $this->load->model('model_user');
                $this->model_user->add_doc($id, $title, $author, $descript, $cate, $user, $tags, $location);
                $this->model_user->add_tags($id, $tags, $location);

                    $x = $zip->open($myFile);
                    if ($x === TRUE) {
                    $zip->extractTo('./assets/resource/'.$id);
                    $zip->close();
                    unlink($myFile);        
                    $msg = 'Your file uploaded and unziped.';
                    } else {
                    $msg = 'Please upload epub or zip file!';
                    }
                    
                }            
                $this->session->set_flashdata('msg',$msg);  
               // $this->load->view('upload_success_view', $data); 
              
                 redirect(base_url().'user');        
            }           
        }  
        else
            redirect(base_url()."home");        
    }

//====================================================================================   
//==============================LOGIN FUNCTION========================================
//====================================================================================
    public function get_login(){                       
        $user = $this->input->post('user');
        $pass = $this->input->post('pass');
        $passmd5 = md5($pass);

        $data['template']['menu'] = createMenu();
        $data['error'] = ' ';
        $this->load->model('model_user');

        $q = $this->model_user->check_login($user, $passmd5);

        if (!is_numeric($q)) 
        {

            $catchSession = array(
                'username' => $this->input->post('user'),
                'is_logged_in' => true
            );
            $this->session->set_userdata($catchSession);

            echo 'dang nhap thanh cong';
            // redirect(base_url().'user');
        }  
        else 
        {
            echo 'khong dung'. $user ;

            // $this->load->view('view_user_login');

        }
    // }
    }

//====================================================================================   
//=============================LOGOUT FUNCTION========================================
//====================================================================================

        public function logout(){
            if($this->is_login()){
                $this->session->unset_userdata(array('username'=>'', 'is_logged_in'=>false));
                redirect(base_url().'home');
        }
    }

//====================================================================================   
//=============================EDIT FUNCTION========================================
//====================================================================================
     public function show_profile(){
        if($this->is_login()){
            $q = $this->session->userdata('username');
            $this->load->model('model_user');
            $data['profile'] = $this->model_user->show_profile($q);
        }
        else
            redirect(base_url()."user");

        $data['template']['menu'] = createMenu();
        if($this->is_login())
            $data['template']['user'] = $this->session->userdata('username');
        $this->load->view('view_user_edit', $data);
    }

    public function update_profile(){
        if($this->is_login()){
            $username = $this->session->userdata('username');
            $fullname = $this->input->post('fullname');
            $gender = $this->input->post('gender');
            $dob = $this->input->post('dob');
            $phone = $this->input->post('phone');
            $job = $this->input->post('job');
            $care = $this->input->post('interestedin');

            $this->load->model('model_user');
            $this->model_user->update_profile($username, $fullname, $gender, $dob, $phone, $job, $care);
            redirect(base_url()."user");
        }
        else            
            redirect(base_url()."user");

        $data['template']['menu'] = createMenu();
        if($this->is_login())
            $data['template']['user'] = $this->session->userdata('username');
        $this->load->view('view_user_edit', $data);
        
    }
//=========================================================================
    public function remove_reading() {
        $user = $this->session->userdata('username');
        $book = $this->input->post('book');

        $this->load->model('model_user');
        $this->model_user->remove_reading($book, $user);
        echo $user.' - '.$book;
    }

}
